package com.fingard.dsp.bank.directbank.bos01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;

import java.io.File;
import java.util.*;

/**
 * @author Parker on 2019-08-06.
 * @version 1.0
 */
public class BOS01Receipt extends BOS01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        //电子回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt, retAts);
                } else {
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    retAts.respCode = "-1";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    private void download(ReqQryReceipt p_reqReceipt, RetAtsReceipt retAts) {
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

            int tmpFileCount = 0;//上传回单数量
            StringBuilder json = new StringBuilder();
            json.append("transType=downloadreceipt&data={\"rows\":[");
            //按日循环
            while (tmpIntFrom <= tmpIntTo && StringHelper.isNullOrEmpty(retAts.respCode)) {
                int start = 1;//如果有多个文件,需要下载多次
                int fileCount = 0;//文件总数
                List<Map<String, String>> billInfoList = new ArrayList<Map<String, String>>();
                do {
                    String[] tmpStrRet = downloadReceipt(getQryTransID(), p_reqReceipt.actNum, String.valueOf(tmpIntFrom), start);
                    //String[] tmpStrRet = new String[]{"", "D:\\WorkSpace\\IDEA\\dsp\\dsp-service\\src\\main\\tempfile\\201908\\07\\BOS01\\DOWNRECEIPT\\00009000356_20190710_1_2.zip"};
                    if (tmpStrRet[0].length() == 0) {
                        if (tmpStrRet[1].contains(".zip")) {
                            //00009000356_20190710_1_1
                            String fileName = tmpStrRet[1].substring(tmpStrRet[1].lastIndexOf(File.separator) + 1, tmpStrRet[1].lastIndexOf(".zip"));//00009000356_20190710_1_1
                            String[] fileNameArrs = fileName.split("_");
                            fileCount = Integer.parseInt(fileNameArrs[3]);

                            //文件解压路径
                            String localDir = getTempFileDirectory() + File.separator + "DOWNRECEIPT" + File.separator + tmpIntFrom;
                            WriteBankLogLn("文件下载已完成，开始解压...");
                            WriteBankLogLn("解压至：[" + localDir + "]");
                            ZipHelper.unzipFile(tmpStrRet[1], localDir);
                            WriteBankLogLn("文件解压已完成.");
                            String destPath = localDir + File.separator + fileName;
                            String[] files = FileHelper.listFiles(destPath);
                            if (files == null || files.length == 0) {
                                WriteBankLogLn("解压后文件夹" + destPath + "下为空");
                                continue;
                            }
                            //删除压缩包
                            if (FileHelper.deleteFileIfExists(tmpStrRet[1])) {
                                WriteBankLogLn("已删除临时文件：" + tmpStrRet[1]);
                            }
                            for (String file : files) {
                                if (file.equals(fileNameArrs[0] + "_" + fileNameArrs[1] + ".txt")) {//回单汇总文件
                                    String context = FileHelper.readFileText(destPath + File.separator + file, "UTF-8");
                                    String[] billCount = context.split("\n");
                                    for (String bill : billCount) {
                                        StringBuilder tmpSbMsg = new StringBuilder();
                                        XmlTextReader tmpBkReader = loadBankRespXmlReader(bill, tmpSbMsg);
                                        if (tmpBkReader != null) {
                                            Map<String, String> tmpMap = new HashMap<String, String>();
                                            tmpMap.put("BillCode", tmpBkReader.getFirstText("/BillCode"));//回单编号
                                            tmpMap.put("PAY_ACCOUNT", tmpBkReader.getFirstText("/DATA/PAY_ACCOUNT"));//支付账号
                                            tmpMap.put("PAY_ACCOUNT_NAME", tmpBkReader.getFirstText("/DATA/PAY_ACCOUNT_NAME"));//支付名称
                                            tmpMap.put("RECV_ACCOUNT", tmpBkReader.getFirstText("/DATA/RECV_ACCOUNT"));//收方账号
                                            tmpMap.put("RECV_ACCOUNT_NAME", tmpBkReader.getFirstText("/DATA/RECV_ACCOUNT_NAME"));//收方名称
                                            tmpMap.put("LOWER_MONEY", tmpBkReader.getFirstText("/DATA/LOWER_MONEY"));//金额
                                            billInfoList.add(tmpMap);
                                        } else {
                                            WriteBankLogLn("回单汇总文件内容有误");
                                            retAts.writeRespCode("-1");
                                            retAts.writeRespInfo("回单汇总文件内容有误");
                                            break;
                                        }
                                    }
                                } else {
                                    //上传共享目录
                                    if ((file.endsWith(".PDF") || file.endsWith(".pdf"))) {
                                        int result = -1;
                                        WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                        String tmpByDate = Format.Date8Format.format(new Date());
                                        tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                                + p_reqReceipt.reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                        if (new File(destPath + File.separator + file).exists()) {
                                            WriteBankLogLn(
                                                    "正在上传文件至共享目录1:" + tmpByDate + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(destPath + File.separator + file, tmpByDate,
                                                    FGBiz.dspCenter.dspSet.receiptShareDir);
                                        }
                                        if (result == 0 || result == 1) {
                                            if (result == 0) {
                                                WriteBankLogLn("文件上传成功");
                                                tmpFileCount++;
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            Iterator<Map<String, String>> iterator = billInfoList.iterator();
                                            while (iterator.hasNext()) {
                                                Map<String, String> tmpMap = iterator.next();
                                                if (tmpMap.get("BillCode").equals(file.substring(0, file.lastIndexOf(".")))) {
                                                    iterator.remove();
                                                    // 推送数据给ATS处理
                                                    json.append("{");
                                                    json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                                    json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                                    json.append("\"receiptCode\":\"" + tmpMap.get("BillCode") + "\",");
                                                    json.append("\"receiptType\":\"" + "" + "\",");
                                                    json.append("\"receiptState\":\"" + "" + "\",");
                                                    if (p_reqReceipt.actNum.equals(tmpMap.get("RECV_ACCOUNT"))) {
                                                        json.append("\"oppActName\":\"" + tmpMap.get("PAY_ACCOUNT_NAME") + "\",");
                                                        json.append("\"oppActNum\":\"" + tmpMap.get("PAY_ACCOUNT") + "\",");
                                                        json.append("\"moneyway\":\"" + "2" + "\",");
                                                    } else {
                                                        json.append("\"oppActName\":\"" + tmpMap.get("RECV_ACCOUNT_NAME") + "\",");
                                                        json.append("\"oppActNum\":\"" + tmpMap.get("RECV_ACCOUNT") + "\",");
                                                        json.append("\"moneyway\":\"" + "1" + "\",");
                                                    }
                                                    json.append("\"amount\":\"" + "" + tmpMap.get("LOWER_MONEY") + "\",");
                                                    json.append("\"tranSeqNo\":\"" + "" + "\",");
                                                    json.append("\"tranCode\":\"" + "" + "\",");
                                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(tmpCalendarFrom.getTime()) + "\",");
                                                    json.append("\"filePath\":\"" + tmpByDate
                                                            + StringHelper.getFileName(file) + "\",");
                                                    json.append("\"fileType\":\"1\"");
                                                    json.append("},");
                                                    break;
                                                }
                                            }
                                        } else {
                                            WriteBankLogLn(tmpIntFrom + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                            retAts.respCode = "-1";
                                            retAts.respInfo = tmpIntFrom + ":上传文件至共享目录失败，请检查共享目录配置是否正确";
                                            break;
                                        }
                                    } else {
                                        WriteBankLogLn("文件格式不正确");
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "文件格式不正确";
                                        return;
                                    }
                                }
                            }
                        }else{
                            WriteBankLogLn("银行返回结果:\r\n:" + Arrays.toString(tmpStrRet));
                            WriteBankLogLn(tmpIntFrom + "无回单数据.");
                            break;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpStrRet[1];
                        return;
                    }
                } while (start++ < fileCount);


                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }

            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");

            json.append("]}");
            if (tmpFileCount > 0) {
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
        }
    }
}
